<?php
namespace app\index\controller;

use think\admin\Controller;
//use think\Db;
use think\facade\Db;
use think\facade\Validate;

require_once VENDOR_PATH . 'WxDecode/wxBizDataCrypt.php';
require_once VENDOR_PATH . 'WxDecode/errorCode.php';


class User extends Controller
{


//    private $appid = "wxf292be732ab7fa35";
//    private $appsecret = "4a628cd7e46045f72c553b242df69975";

    function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

    public function wxDecode(){
        // 接收参数
        $data = request() -> param();
//        $appid = sysconf('wxapp_appid');
//        $appsecret = sysconf('wxapp_appkey');

        $grant_type = "authorization_code";
        $code = $data['code'];
        $encryptedData=$data['encryptedData'];
        $iv = $data['iv'];
        $signature = $data['signature'];
        $rawData = $data['rawData'];
        // 拼接url
        $url = "https://api.weixin.qq.com/sns/jscode2session?"."appid=".$this->appid."&secret=".$this->appsecret."&js_code=".$code."&grant_type=".$grant_type;
        $res = json_decode($this->httpGet($url),true);
        $sessionKey = $res['session_key']; //取出json里对应的值
        $signature2 = sha1(htmlspecialchars_decode($rawData).$sessionKey);
        // 验证签名
        if ($signature2 !== $signature){
            return json("验签失败");
        }
        // 获取解密后的数据
        $pc = new \WXBizDataCrypt($this->appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            return json($data);
        } else {
            $this->error('登录失败');
        }
    }

    public function login(){
        $params = $this->request->post();
        if (isset($params['code'])) {
//            $appid = sysconf('wxapp_appid');
//            $secret = sysconf('wxapp_appkey');
            $api = "https://api.weixin.qq.com/sns/jscode2session";

            //$api,['appid'=>$this->appid,'secret'=>$this->appsecret,'js_code'=>$params['code'],'grant_type'=>'authorization_code']
            //发送
            $str_json = $this->httpGet($api.'?appid='.$this->appid .'&secret='.$this->appsecret.'&js_code='.$params['code']."&grant_type=authorization_code");
            $str = json_decode($str_json,true);
            if(!empty($str['errcode']) || empty($str['openid'])){
                $this->error('获取openid失败，请删除小程序重试',$str);
            }else{
                $user = Db::name("member")->where('openid',$str['openid'])->find();
                if(!$user){
                    $user['id'] = Db::name("member")->insertGetId(['openid'=>$str['openid'],'avatar_image'=>'/uploads/defalt_avatar/male.png','status'=>'normal']);
                }
                $this->success('获取成功',$str);
            }
        }else{
            return $this->error('参数缺失');
        }
    }


    public function getUserNumber(){
        $params = input('post.');

        $appid = sysconf('wxapp_appid');
        $sesson_key = $params['session_key'];
        // 解密，查看官方给的示例文件
        $pc = new WXBizDataCrypt($appid,$sesson_key);
        $encryptedData = $params['encryptedDataStr'];
        $iv = $params['iv'];
        $pc->decryptData($encryptedData, $iv, $encryptedData);
        $decode_data = json_decode($decode_data,true);
        if(!empty($decode_data['purePhoneNumber'])){
            $user = Db::name("member")->where('openid',$params['openid'])->find();
            if(!$user){
                $this->error("用户不存在");
            }else{
                if(!empty($user['mobile'])){
                    if($user['mobile'] != $decode_data['purePhoneNumber']){
                        $this->error('此微信已经被其它手机号绑定');
                    }
                }else{
                    Db::name('user')->where('id',$user['id'])->update([
                        'mobile'=>$decode_data['purePhoneNumber'],
                        'avatar_image'=>'/uploads/defalt_avatar/male.png'
                    ]);
                }
            }
            $ret = $this->auth->direct($user['id']);
            if($ret){
                $this->success('登录成功',['userInfo'=>$this->auth->getUserinfo()]);
            }else{
                $this->error('登录失败');
            }
        }else{
            $this->error('微信登录过期，请删除小程序重新打开',['type'=>'decodeErr',$decode_data,$params]);
        }
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 用户信息
     */
    public function userinfo(){
        $userinfo = Db::name('data_member')->where('id='.MID)->find();
        if (empty($userinfo) || $userinfo['deleted'] == 1){
            $this->error('未获取到用户信息或者该用户已被删除');
        }else{
            $userinfo['like'] = Db::name('data_member_like')->where(['user_id' => MID,'type' => 1])->count();
            $userinfo['track'] = Db::name('data_member_like')->where(['user_id' => MID,'type' => 2])->count();
            $userinfo['praise'] = Db::name('data_member_like')
                ->alias('a')
                ->join('shop_goods b','a.user_id=b.user_id')
                ->where('a.user_id',MID)
                ->count();
            $this->success('获取成功',$userinfo);
        }
    }

    /**
     * @throws \think\db\exception\DbException
     * 我的足迹
     */
    public function myTracks(){
        $where = [
            'b.user_id'   => MID,
            'type'      => 2,
        ];
        $track = Db::name('data_member_like')
            ->alias('a')
            ->join('shop_goods b','a.a_id = b.id')
            ->field('b.*')
            ->order("create_at desc")
            ->where($where)
            ->paginate(sysconf('listrow'));
        if (!empty($track)){
            $this->success('获取成功',$track);
        }else{
            $this->error('获取失败');
        }
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 我的作品
     */
    public function myWorks(){
        $data = input();
        $where = [
//            'type'      => $data['type'],
            'user_id'   => MID,
            'deleted'   => 0,
            'status'    => 1
        ];
        $lists = Db::name('shop_goods')
            ->where($where)
            ->field('id,code,name,mark,remark,content,num_collect,create_at')
            ->paginate(sysconf('listRow'));
        if (!empty($lists)){
            $this->success('获取成功',$lists);
        }else{
            $this->error('获取失败');
        }
    }

    /**
     * @throws \think\db\exception\DbException
     * 用户消息
     */
    public function myMessage(){
        $list = Db::name("data_user_message")->field('content,create_at,status')->where('user_id='. MID)->paginate(sysconf('listrow'));
        if (!empty($list)){
            $this->success('获取成功',$list);
        }else{
            $this->error('获取失败');
        }
    }

    public function myComment(){
//        $list = Db::name('')
    }
}